"ui";
engines.all().map((ScriptEngine) => {
  if (engines.myEngine().toString() !== ScriptEngine.toString()) {
    ScriptEngine.forceStop();
  }
});
let port = "34567";
let url = "http://127.0.0.1:" + port + "/";
// let url = "http://192.168.101.24:" + port + "/";

startServer();
let imgPath = "./man1.jpg";
let imgPath2 = "./man2.jpg";
let imgPath3 = "./girl01.jpg";
let imgPath4 = "./girl02.jpg";
let img = images.read(files.path(imgPath));
let img2 = images.read(files.path(imgPath2));
let img3 = images.read(files.path(imgPath3));
let img4 = images.read(files.path(imgPath4));
let imgBase64 = images.toBase64(img);
let img2Base64 = images.toBase64(img2);
let img3Base64 = images.toBase64(img3);
let img4Base64 = images.toBase64(img4);
$ui.layout(
  <vertical>
    <scroll>
      <vertical>
        <vertical>
          <horizontal>
            <vertical>
              <img id="img3" src="file://{{imgPath3}}"></img>
              <text id="img3Data"></text>
            </vertical>
            <vertical>
              <img id="img4" src="file://{{imgPath4}}"></img>
              <text id="img4Data"></text>
            </vertical>
          </horizontal>
          <button id="SegmentPortraitPic">人像分割</button>
          <button id="DetectBodyJoints">人体关键点分析</button>
          <button id="DetectBody">人体检测与属性分析</button>
        </vertical>
        <vertical>
          <horizontal>
            <img id="img" src="file://{{imgPath}}"></img>
            <img id="img2" src="file://{{imgPath2}}"></img>
          </horizontal>
          <seekbar id="seekbar" progress="30" w="*" margin="20 10 20 0" />
          <horizontal w="*" gravity="center">
            <text text="1. 修改年龄: " textSize="20sp"></text>
            <text id="age" textSize="20sp">
              30
            </text>
          </horizontal>
          <horizontal w="*" gravity="center" marginTop="10">
            <text text="2. 修改性别: " textSize="20sp"></text>
            <radiogroup id="gender" orientation="horizontal">
              <radio text="男"></radio>
              <radio text="女"></radio>
            </radiogroup>
          </horizontal>
          <button id="cartoon" text="3. 人像动漫化"></button>
          <button id="morph" bg="#bcaaa4" text="4.1 人像渐变任务提交"></button>
          <text id="JobId" textSize="20sp" w="*" gravity="center">
            JobId
          </text>
          <button id="morph2" bg="#8d6e63" text="4.2 人像渐变任务查询(请求频率限制20次/秒)"></button>
          <VideoView id="video" w="wrap_content" layout_gravity="center" bg="#ffffff" />
        </vertical>
      </vertical>
    </scroll>
  </vertical>
);
$ui.video.setZOrderOnTop(true);

$ui.DetectBody.click(function () {
  DetectBody(img3Base64, $ui.img3Data);
  DetectBody(img4Base64, $ui.img4Data);
});
$ui.DetectBodyJoints.click(function () {
  DetectBodyJoints(img4Base64, $ui.img4, img4);
});
$ui.SegmentPortraitPic.click(function () {
  SegmentPortraitPic(img3Base64, $ui.img3);
  SegmentPortraitPic(img4Base64, $ui.img4);
});

$ui.morph.click(function () {
  morphFace([imgBase64, img2Base64, imgBase64, img2Base64]);
});
$ui.morph2.click(function () {
  morphFace2();
});

$ui.cartoon.click(function () {
  cartoonFace(imgBase64, $ui.img);
  cartoonFace(img2Base64, $ui.img2);
});

$ui.seekbar.setOnSeekBarChangeListener(
  new android.widget.SeekBar.OnSeekBarChangeListener({
    onStopTrackingTouch: function (seekbar) {
      let age = seekbar.getProgress();
      toastLog("年龄: " + age);
      $ui.age.setText(age + "");
      changeAge(age, imgBase64, $ui.img);
      changeAge(age, img2Base64, $ui.img2);
    },
  })
);

$ui.gender.setOnCheckedChangeListener(function (radioGroup, id) {
  let view = $ui.findView(id);
  let gender = view.getText().toString();
  toastLog(gender);
  let Gender = gender === "男" ? 1 : 0;
  changeGender(Gender, imgBase64, $ui.img);
  changeGender(Gender, img2Base64, $ui.img2);
});

events.on("exit", function () {
  img.recycle();
  img2.recycle();
});

/* ---------------------自定义函数----------------------------------------------------- */
function startServer() {
  $engines.execScriptFile("/storage/emulated/0/脚本/ft/ft/index.js");
  events.on("exit", function () {
    let r = http.get(url + "exit");
    log(r.body.string());
  });
}
function morphFace2() {
  let JobId = $ui.JobId.text().replace("JobId: ", "");
  if (JobId.length < 10) {
    toastLog("JobId 长度小于10, 不正确");
    return true;
  }
  let body = {
    action: "QueryFaceMorphJob",
    JobId: JobId,
  };

  http.postJson(
    url,
    body,
    {
      headers: {
        "Content-Type": "application/json",
      },
    },
    function (res, err) {
      if (err) {
        log("morphFace 异常");
        console.error(err);
        return;
      }
      let obj = res.body.json();
      toastLog(obj.JobStatus);
      if (obj.JobStatus === "处理完成") {
        toastLog("下载中, 完成后自动播放");
        showVideo(obj.FaceMorphOutput.MorphUrl);
      }

      // { JobStatus: "处理中", FaceMorphOutput: null, RequestId: "d3fd2a76-a60a-4e6b-af7a-c8fb7053c066" };

      // {
      //   JobStatus: "处理完成",
      //   FaceMorphOutput: {
      //     MorphUrl:
      //       "http://bda-video-bodyseg-1254418846.cos.ap-guangzhou.myqcloud.com/video_morph_prod/1/1304656192/20211006085822_f080ece5-74fb-4dca-b3c6-de33da49b2b0_result.mp4",
      //     MorphMd5: "6028BB3E8C025447279D7EA993C54894",
      //     CoverImage: "",
      //   },
      //   RequestId: "d4b1c970-a128-457c-a470-c043d1659670",
      // };
    }
  );
}
function showVideo(url) {
  log(url);
  http.get(url, {}, function (res, err) {
    if (err) {
      log("下载视频异常");
      console.error(err);
      return;
    }
    let tempPath = files.join(files.getSdcardPath(), "脚本", "temp.mp4");
    files.writeBytes(tempPath, res.body.bytes());
    $ui.post(function () {
      $ui.video.setVideoPath(tempPath);
      $ui.video.start();
    });
  });
}
function morphFace(Images) {
  let body = {
    action: "MorphFace",
    Images: Images,
  };
  http.postJson(
    url,
    body,
    {
      headers: {
        "Content-Type": "application/json",
      },
    },
    function (res, err) {
      if (err) {
        log("morphFace 异常");
        console.error(err);
        return;
      }
      let obj = res.body.json();
      toastLog(obj);
      $ui.JobId.setText("JobId: " + obj.JobId);
      // {"JobId":"x0j7mbcuqQARRVPx","EstimatedProcessTime":30,"RequestId":"bd331bd0-34e9-41b9-b97c-338603dae739"}
    }
  );
}

function drawKeyPoint(view, res, img) {
  /* -------------------------------------------------------------------------- */
  var canvas = new Canvas(img);
  var paint = new Paint();
  paint.setStyle(Paint.Style.STROKE);
  paint.setStrokeWidth(20);
  paint.setTextSize(50);
  paint.setColor(colors.parseColor("#ff0000"));
  /* -------------------------------------------------------------------------- */
  let BodyJointsResults = res.BodyJointsResults;
  var len = BodyJointsResults.length;
  for (var i = 0; i < len; i++) {
    let body = BodyJointsResults[i];
    let BoundBox = body.BoundBox;
    canvas.drawRect(BoundBox.X, BoundBox.Y, BoundBox.X + BoundBox.Width, BoundBox.Y + BoundBox.Height, paint);
    // BoundBox: {
    //   Width: 425,
    //   X: 215,
    //   Height: 1327,
    //   Y: -53,
    // },

    let BodyJoints = body.BodyJoints;
    var BodyJointsLen = BodyJoints.length;
    for (var j = 0; j < BodyJointsLen; j++) {
      let KeyPoint = BodyJoints[j];
      let KeyPointType = KeyPoint.KeyPointType;
      let x = KeyPoint.X;
      let y = KeyPoint.Y;
      canvas.drawPoint(x, y, paint);
      paint.setStrokeWidth(3);
      paint.setStyle(Paint.Style.FILL);
      canvas.drawText(KeyPointType, x, y, paint);
      paint.setStyle(Paint.Style.STROKE);
      paint.setStrokeWidth(20);
      // {
      //   KeyPointType: "头部",
      //   X: 418.2265625,
      //   Y: 65.0546875,
      // },
    }
  }
  var image = canvas.toImage();
  ui.run(function () {
    view.setImageBitmap(image.bitmap);
  });
}

function showDetectBody(view, data) {
  let BodyDetectResults = data.BodyDetectResults;
  var len = BodyDetectResults.length;
  let arr = [];
  for (var i = 0; i < len; i++) {
    let BodyAttributeInfo = BodyDetectResults[i].BodyAttributeInfo;
    let itemData = [];

    for (var k in BodyAttributeInfo) {
      if (k === "UpperBodyCloth" || k === "LowerBodyCloth") {
        let obj = BodyAttributeInfo[k];
        for (var k2 in obj) {
          itemData.push(k2 + ": " + obj[k2].Type);
        }
      } else {
        itemData.push(k + ": " + BodyAttributeInfo[k].Type);
      }
    }
    arr.push(itemData.join("\n"));
  }
  ui.run(function () {
    view.setText(arr.join("\n"));
  });
}
function DetectBody(imgBase64, view) {
  let body = {
    action: "DetectBody",
    imgBase64: imgBase64,
  };
  http.postJson(
    url,
    body,
    {
      headers: {
        "Content-Type": "application/json",
      },
    },
    function (res, err) {
      if (err) {
        console.log("DetectBody 响应异常");
        console.log(err);
        return false;
      }
      let data = res.body.json();
      showDetectBody(view, data);
    }
  );
}
function DetectBodyJoints(imgBase64, view, img) {
  let body = {
    action: "DetectBodyJoints",
    imgBase64: imgBase64,
  };
  http.postJson(
    url,
    body,
    {
      headers: {
        "Content-Type": "application/json",
      },
    },
    function (res, err) {
      if (err) {
        console.log("DetectBodyJoints 响应异常");
        console.log(err);
        return false;
      }
      let data = res.body.json();
      drawKeyPoint(view, data, img);
    }
  );
}
function SegmentPortraitPic(imgBase64, view) {
  let body = {
    action: "SegmentPortraitPic",
    imgBase64: imgBase64,
  };
  http.postJson(
    url,
    body,
    {
      headers: {
        "Content-Type": "application/json",
      },
    },
    function (res, err) {
      let obj = res.body.json();
      let imgBase64Data = obj.ResultImage;
      let data = "data:image/png;base64," + imgBase64Data;
      // files.write("/sdcard/1.txt", JSON.stringify(obj));
      let img = images.fromBase64(data);
      view.setImageBitmap(img.bitmap);
    }
  );
}
function cartoonFace(imgBase64, view) {
  let body = {
    action: "FaceCartoonPic",
    imgBase64: imgBase64,
  };
  http.postJson(
    url,
    body,
    {
      headers: {
        "Content-Type": "application/json",
      },
    },
    function (res, err) {
      let obj = res.body.json();
      http.get(obj.ResultUrl, {}, function (res, err) {
        if (err) {
          log("下载图片异常");
          console.error(err);
          return;
        }
        let tempPath = files.join(files.getSdcardPath(), "脚本", "temp.jpg");
        files.writeBytes(tempPath, res.body.bytes());
        view.attr("src", "file://" + tempPath);
      });
    }
  );
}
function changeGender(Gender, imgBase64, view) {
  let body = {
    action: "SwapGenderPic",
    Gender: Gender,
    imgBase64: imgBase64,
  };
  http.postJson(
    url,
    body,
    {
      headers: {
        "Content-Type": "application/json",
      },
    },
    function (res, err) {
      let obj = res.body.json();
      http.get(obj.ResultUrl, {}, function (res, err) {
        if (err) {
          log("下载图片异常");
          console.error(err);
          return;
        }
        let tempPath = files.join(files.getSdcardPath(), "脚本", "temp.jpg");
        files.writeBytes(tempPath, res.body.bytes());
        view.attr("src", "file://" + tempPath);
      });
    }
  );
}

function changeAge(age, imgBase64, view) {
  let body = {
    action: "ChangeAgePic",
    age: parseInt(age),
    imgBase64: imgBase64,
  };
  http.postJson(
    url,
    body,
    {
      headers: {
        "Content-Type": "application/json",
      },
    },
    function (res, err) {
      // 返回的结果
      // {"ResultImage":"","ResultUrl":"https://faceeffect-1254418846.cos.ap-guangzhou.myqcloud.com/1304656192/1633478175101/YNh7O2TGyjec2","RequestId":"25795126-543d-4b7c-be99-dbffabc7318b"}
      let obj = res.body.json();
      http.get(obj.ResultUrl, {}, function (res, err) {
        if (err) {
          log("下载图片异常");
          console.error(err);
          return;
        }
        let tempPath = files.join(files.getSdcardPath(), "脚本", "temp.jpg");
        files.writeBytes(tempPath, res.body.bytes());
        view.attr("src", "file://" + tempPath);
      });
    }
  );
}
